/*
 * @Author: mayijun
 * @Date: 2022-05-14 11:12:52
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-18 12:56:07
 */
//表头条件拖拽
import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import './index.scss';
import draggable from 'vuedraggable';
import IndexTag from '../indexTag';
import DimensionTag from '../dimensionTag';
import { ElDivider } from 'element-plus';
import Pagination from '@/components/Pagination';

const TableHeaderDrag = defineComponent({
  name: 'TableHeaderDrag',
  components: { draggable },
  props: {
    tableHeaderList: {
      type: Array,
      default: () => []
    },
    tableData: {
      type: Object,
      default: () => {}
    },
    chosenDimensionIds: {
      type: Array,
      default: () => []
    },
    chosenMetricsIds: {
      type: Array,
      default: () => []
    },
    isMetricsFavorite: {
      type: Boolean,
      default: false
    }
  },
  emits: [
    'filterColomn',
    'removeItem',
    'updateItem',
    'currentChange',
    'pageSizeChange'
  ],
  setup: (props, { slots, attrs, emit }) => {
    //删除对象
    const removeItem = (id: string, index: number) => {
      emit('removeItem', id, index);
    };

    //更新对象
    const updateItem = (item: any, index: any) => {
      emit('updateItem', item, index);
    };

    //上下对齐列的宽度
    const alignColumnWidth = () => {
      props.tableHeaderList.map((item: any, index: any) => {
        let className = '';
        if (item.combinationName) {
          className = 'zh' + index;
        } else {
          if (item.dimensionType) {
            className = item.dimensionType + item.id;
          } else {
            className = 'index' + item.dataTypeId + item.id;
          }
        }

        //获取所有列表的dom对象
        let cells = document.querySelectorAll(`.${className}`);

        let widthList: any[] = [];
        cells.forEach((el: any) => {
          let wh = el.querySelector('.drag-cell')?.clientWidth || 0;
          widthList.push(wh);
        });
        //去表头和内容最大的宽度
        const max = Math.max(...widthList);
        cells.forEach((el: any) => {
          el.setAttribute('width', max + 'px');
        });
      });
    };

    const filterColomn = (item: any) => {
      emit('filterColomn', item);
    };

    const handleCurrentChange = (v: any) => {
      emit('currentChange', v);
    };
    const handlePageSizeChange = (size: any) => {
      emit('pageSizeChange', size);
    };

    watch(
      () => props.tableData,
      (val) => {
        nextTick(() => {
          alignColumnWidth();
        });
      },
      { deep: true }
    );

    return () => {
      return (
        <>
          <table class="dragList-table">
            <thead class="dragList-header">
              <tr class="drag-list">
                {props.tableHeaderList.length == 0 && (
                  <span class="no-data">拖拽左侧元素至画布区域配置逻辑</span>
                )}
                <draggable
                  class="condition-drag"
                  list={props.tableHeaderList}
                  group="people"
                  item-key="id"
                  ghost-class="drag-ghost"
                  onAdd={(val: any) => {
                    //过滤当前对象，并提示重复
                    filterColomn(val.item._underlying_vm_);
                  }}
                  v-slots={{
                    item: (item: any) => {
                      return (
                        <th
                          class={[
                            item.element.combinationName
                              ? 'zh' + item.index
                              : '',
                            !item.element.combinationName &&
                            item.element.dimensionType
                              ? item.element.dimensionType + item.element.id
                              : '',
                            !item.element.combinationName &&
                            item.element.dataTypeId
                              ? 'index' +
                                item.element.dataTypeId +
                                item.element.id
                              : ''
                          ]}
                        >
                          <div class="drag-cell">
                            {item.element.dimensionType && (
                              <DimensionTag
                                index={item.index}
                                itemData={item.element}
                                onRemoveItem={(id: string, index: number) =>
                                  removeItem(id, index)
                                }
                              ></DimensionTag>
                            )}
                            {!item.element.dimensionType && (
                              <IndexTag
                                index={item.index}
                                itemData={item.element}
                                chosenDimensionIds={props.chosenDimensionIds}
                                chosenMetricsIds={props.chosenMetricsIds}
                                isMetricsFavorite={props.isMetricsFavorite}
                                onIndexSubmit={(data) => {
                                  updateItem(data, item.index);
                                }}
                                onSelectChange={(val) => {
                                  item.element['aggregationId'] = val.value;
                                  item.element['aggregation'] = val.label;
                                }}
                                onRemoveItem={(id: string, index: number) =>
                                  removeItem(id, index)
                                }
                              ></IndexTag>
                            )}
                          </div>
                        </th>
                      );
                    }
                  }}
                ></draggable>
              </tr>
            </thead>
            <tbody>
              {props.tableData.list &&
                props.tableData.list.map((obj: any, index: number) => {
                  console.log(props.tableHeaderList);
                  if (obj) {
                    return (
                      <>
                        <tr>
                          {() => {
                            //按照返回对象的顺序展示
                            let rouderArray: any[] = [];
                            // sum avg max min count group
                            let sumObj = {};
                            let avgObj = {};
                            let maxObj = {};
                            let minObj = {};
                            let countObj = {};
                            let groupObj = {};

                            props.tableHeaderList.map(
                              (item: any, index: any) => {
                                if (Array.isArray(item.arithmeticList)) {
                                  item.aggregationId = '80';
                                }
                                switch (Number(item.aggregationId)) {
                                  case 66:
                                    item.aggregationType = 'sum';
                                    sumObj[index] = 0;
                                    break;
                                  case 67:
                                    item.aggregationType = 'avg';
                                    avgObj[index] = 0;
                                    break;
                                  case 77:
                                    item.aggregationType = 'max';
                                    maxObj[index] = 0;
                                    break;
                                  case 78:
                                    item.aggregationType = 'min';
                                    minObj[index] = 0;
                                    break;
                                  case 79:
                                    item.aggregationType = 'count';
                                    countObj[index] =
                                      0;
                                    break;
                                  case 80:
                                    groupObj[index] =
                                      0;
                                    break;
                                }
                              }
                            );

                            props.tableHeaderList.map(
                              (item: any, index: any) => {
                                let content = '';
                                if (Array.isArray(item.arithmeticList)) {
                                  item.aggregationType = 'comb_field';
                                }
                                switch (item.aggregationType) {
                                  case 'sum':
                                    content =
                                      item.enName +
                                      '_' +
                                      item.aggregationType +
                                      sumObj[index];
                                    break;
                                  case 'avg':
                                    content =
                                      item.enName +
                                      '_' +
                                      item.aggregationType +
                                      avgObj[index];
                                    break;
                                  case 'max':
                                    content =
                                      item.enName +
                                      '_' +
                                      item.aggregationType +
                                      maxObj[index];
                                    break;
                                  case 'min':
                                    content =
                                      item.enName +
                                      '_' +
                                      item.aggregationType +
                                      minObj[index];
                                    break;
                                  case 'count':
                                    content =
                                      item.enName +
                                      '_' +
                                      item.aggregationType +
                                      countObj[index];
                                    break;
                                  case 'comb_field':
                                    content =
                                      'comb_field' + '_' + groupObj[index];
                                    break;
                                }

                                console.log(content);

                                let pushDom = (
                                  <td
                                    class={[
                                      item.combinationName ? 'zh' + index : '',
                                      !item.combinationName &&
                                      item.dimensionType
                                        ? item.dimensionType + item.id
                                        : '',
                                      !item.combinationName && item.dataTypeId
                                        ? 'index' + item.dataTypeId + item.id
                                        : ''
                                    ]}
                                  >
                                    <div class="drag-cell">-</div>
                                  </td>
                                );
                                if (obj[content]) {
                                  pushDom = (
                                    <td
                                      class={[
                                        item.combinationName
                                          ? 'zh' + index
                                          : '',
                                        !item.combinationName &&
                                        item.dimensionType
                                          ? item.dimensionType + item.id
                                          : '',
                                        !item.combinationName && item.dataTypeId
                                          ? 'index' + item.dataTypeId + item.id
                                          : ''
                                      ]}
                                    >
                                      <div class="drag-cell">
                                        {obj[content]}
                                      </div>
                                    </td>
                                  );
                                }
                                //兼顾非指标类型 || 组合类型数据
                                if (obj[item.enName]) {
                                  pushDom = (
                                    <td
                                      class={[
                                        item.combinationName
                                          ? 'zh' + index
                                          : '',
                                        !item.combinationName &&
                                        item.dimensionType
                                          ? item.dimensionType + item.id
                                          : '',
                                        !item.combinationName && item.dataTypeId
                                          ? 'index' + item.dataTypeId + item.id
                                          : ''
                                      ]}
                                    >
                                      <div class="drag-cell">
                                        {obj[item.enName]}
                                      </div>
                                    </td>
                                  );
                                }

                                rouderArray.push(pushDom);
                              }
                            );
                            return rouderArray;
                          }}
                        </tr>
                        <ElDivider></ElDivider>
                      </>
                    );
                  }
                })}
            </tbody>
          </table>
          {props.tableData.list[0] && props.tableData.total > 0 && (
            <div class="Pagination">
              <Pagination
                onCurrentChange={handleCurrentChange}
                onSizeChange={handlePageSizeChange}
                total={Number(props.tableData.total)}
                currentPage={props.tableData.pageNum}
                pageSize={props.tableData.pageSize}
              />
            </div>
          )}
        </>
      );
    };
  }
});

export default TableHeaderDrag;
